package com.whlilong.jxc.filemanager.editor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;

import com.whlilong.jxc.db.DbManager;
import com.whlilong.jxc.dialog.StaffInfoCreate;
import com.whlilong.jxc.editor.support.StaffInfoEditorSupport;
import com.whlilong.jxc.listener.IEditorListener;
import com.whlilong.jxc.model.Yginfo;
import com.whlilong.jxc.print.IconSource;
import com.whlilong.jxc.print.PDocument;
import com.whlilong.jxc.print.PHLine;
import com.whlilong.jxc.print.PTableBoxProvider;
import com.whlilong.jxc.print.PTextBox;
import com.whlilong.jxc.print.PVSpace;
import com.whlilong.jxc.print.PrintPreview;
import com.whlilong.jxc.print.SWTPTable;
import com.whlilong.jxc.service.editor.IEditorService;
import com.whlilong.jxc.sys.ExtentionInfo;
import com.whlilong.jxc.sys.SetTableColColorListener;
import com.whlilong.jxc.treemodel.StaffInfoTreeChildren;
import com.whlilong.jxc.treemodel.StaffInfoTreeParent;
import com.whlilong.jxc.ui.provider.StaffInfoContentProvider;
import com.whlilong.jxc.ui.provider.StaffInfoLabelProvider;
import com.whlilong.jxc.ui.provider.StaffInfoTreeContentProvider;
import com.whlilong.jxc.ui.provider.StaffInfoTreeLabelProvider;
import com.whlilong.jxc.ui.sorter.BrandInfoSorter;

/**
 * 员工信息编辑器
 * 
 * @author sjy
 * 
 */
public class StaffInfoEditor extends AbstractEditor implements IEditorService,
		IEditorListener {

	private Table table;
	protected ExtentionInfo extentionInfo = null;
	private Label infoLabel;
	private Label staffNoLabel;
	private Text staffNoText;
	private Label staffNameLabel;
	private Text staffNameText;
	private Button findBt;
	protected String staffId;
	protected String staffName;
	private List<Yginfo> list = new ArrayList<Yginfo>();
	private Shell shell;
	private boolean isSave = true;

	public StaffInfoEditor() {
		// TODO Auto-generated constructor stub
	}

	public Control createGroupText(Composite parent) {

		Composite container = new Composite(parent, SWT.NONE);
		final GridLayout gl = new GridLayout(2, false);
		container.setLayout(gl);
		createTreeViewer(container);
		createTableViewer(container);
		return container;
	}

	private void createTreeViewer(Composite parent) {
		// TODO Auto-generated method stub
		treeViewer = new TreeViewer(parent, SWT.BORDER | SWT.V_SCROLL
				| SWT.FULL_SELECTION);
		treeViewer.setUseHashlookup(true);

		GridData gd = new GridData();
		gd.verticalAlignment = SWT.TOP;
		final Tree tree = treeViewer.getTree();
		tree.setLayoutData(new GridData(GridData.FILL_VERTICAL));
		final TreeColumn category = new TreeColumn(tree, SWT.LEFT);
		category.setText("员工信息");
		category.setWidth(100);

		treeViewer.setContentProvider(new StaffInfoTreeContentProvider());
		treeViewer.setLabelProvider(new StaffInfoTreeLabelProvider());
		treeViewer.setInput(extentionInfo.getInstance().getStaffTreeInfo());

		tree.setHeaderVisible(true);
		tree.setLinesVisible(true);

		treeViewer.expandToLevel(2);

		treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {

			@Override
			public void selectionChanged(SelectionChangedEvent event) {
				// TODO Auto-generated method stub
				IStructuredSelection selection = (IStructuredSelection) event
						.getSelection();
				if (selection.getFirstElement() instanceof StaffInfoTreeChildren) {
					StaffInfoTreeChildren ktc = (StaffInfoTreeChildren) selection
							.getFirstElement();
					String id = ktc.getStaff().getYgid();
					tableViewer.getTable().clearAll();
					tableViewer.setInput(getStaffinfo(id, null));
				}
				if (selection.getFirstElement() instanceof StaffInfoTreeParent) {
					initial();
					tableViewer.getTable().clearAll();
					tableViewer.setInput(list);
				}

			}
		});

	}

	protected void initial() {
		infoLabel.setForeground(Display.getCurrent().getSystemColor(
				SWT.COLOR_BLUE));
		infoLabel.setText("添加，删除，查询相关数据。。。");
		list = getStaffinfo(null, null);
	}

	protected List getStaffinfo(String id, String name) {
		List<Yginfo> newlist = new ArrayList<Yginfo>();
		int[] idBuffer = { 0 };
		int[] idBuffer2 = { 0, 1 };
		Object[] idObject = { id };
		Object[] nameObject = { name };
		Object[] object = { id, name };
		if (id == null && name == null) {
			newlist = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.sys.getstaffinfo");
		} else if (id != null && name == null) {
			newlist = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.ui.getstaffid", idBuffer, idObject);
		} else if (id == null && name != null) {
			newlist = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.ui.getstaffname", idBuffer, nameObject);
		} else {
			newlist = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.ui.getstaff", idBuffer2, object);
		}
		return list = newlist;
	}

	private void createTableViewer(Composite parent) {
		// TODO Auto-generated method stub
		Composite composite = new Composite(parent, SWT.NONE);
		GridLayout gl = new GridLayout(4, false);
		composite.setLayout(gl);
		composite.setLayoutData(new GridData(GridData.FILL_BOTH));

		infoLabel = new Label(composite, SWT.NONE);
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.heightHint = 20;
		gd.horizontalSpan = 4;
		infoLabel.setLayoutData(gd);

		gd = new GridData();
		gd.widthHint = 100;
		gd.heightHint = 20;
		staffNoLabel = new Label(composite, SWT.RIGHT);
		staffNoLabel.setText("员工编号：");
		staffNoLabel.setLayoutData(gd);
		staffNoText = new Text(composite, SWT.BORDER);
		staffNoText.setLayoutData(gd);

		staffNameLabel = new Label(composite, SWT.RIGHT);
		staffNameLabel.setText("员工姓名：");
		staffNameLabel.setLayoutData(gd);
		staffNameText = new Text(composite, SWT.BORDER);
		staffNameText.setLayoutData(gd);

		findBt = new Button(composite, SWT.NONE);
		findBt.setText("查询 ");
		findBt.setLayoutData(gd);
		findBt.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseDown(MouseEvent e) {
				// TODO Auto-generated method stub
				staffId = staffNoText.getText();
				staffName = staffNameText.getText();
				find(staffId, staffName);
			}

		});

		tableViewer = new TableViewer(composite, SWT.BORDER | SWT.H_SCROLL
				| SWT.FULL_SELECTION);
		tableViewer.setUseHashlookup(true);

		gd = new GridData(GridData.FILL_BOTH);
		gd.horizontalSpan = 4;
		table = tableViewer.getTable();
		table.setLayoutData(gd);
		table.setToolTipText("点击单元格对数据进行修改！");
		// 设置行高
		table.addListener(SWT.MeasureItem, new Listener() {
			public void handleEvent(Event event) {
				event.height = 20;
			}
		});

		StaffInfoEditorSupport editingSupport = new StaffInfoEditorSupport(
				tableViewer, 1, this);
		createColumn("ID", BrandInfoSorter.ID_ASC, BrandInfoSorter.ID_DESC,
				editingSupport);

		editingSupport = new StaffInfoEditorSupport(tableViewer, 2, this);
		createColumn("员工编号", BrandInfoSorter.sbid_asc,
				BrandInfoSorter.sbid_desc, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new StaffInfoEditorSupport(tableViewer, 3, this);
		createColumn("员工姓名", BrandInfoSorter.NAME_ASC,
				BrandInfoSorter.NAME_DESC, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new StaffInfoEditorSupport(tableViewer, 4, this);
		createColumn("部门名称", BrandInfoSorter.NAME_ASC,
				BrandInfoSorter.NAME_DESC, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new StaffInfoEditorSupport(tableViewer, 5, this);
		createColumn("性别", BrandInfoSorter.NAME_ASC, BrandInfoSorter.NAME_DESC,
				editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new StaffInfoEditorSupport(tableViewer, 6, this);
		createColumn("状态", BrandInfoSorter.NAME_ASC, BrandInfoSorter.NAME_DESC,
				editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new StaffInfoEditorSupport(tableViewer, 7, this);
		createColumn("身份证号", BrandInfoSorter.NAME_ASC,
				BrandInfoSorter.NAME_DESC, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new StaffInfoEditorSupport(tableViewer, 8, this);
		createColumn("员工权限", BrandInfoSorter.NAME_ASC,
				BrandInfoSorter.NAME_DESC, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new StaffInfoEditorSupport(tableViewer, 9, this);
		createColumn("入职时间", BrandInfoSorter.NAME_ASC,
				BrandInfoSorter.NAME_DESC, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new StaffInfoEditorSupport(tableViewer, 10, this);
		createColumn("职位", BrandInfoSorter.NAME_ASC, BrandInfoSorter.NAME_DESC,
				editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new StaffInfoEditorSupport(tableViewer, 11, this);
		createColumn("生日", BrandInfoSorter.NAME_ASC, BrandInfoSorter.NAME_DESC,
				editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new StaffInfoEditorSupport(tableViewer, 12, this);
		createColumn("学历", BrandInfoSorter.NAME_ASC, BrandInfoSorter.NAME_DESC,
				editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new StaffInfoEditorSupport(tableViewer, 13, this);
		createColumn("联系电话", BrandInfoSorter.NAME_ASC,
				BrandInfoSorter.NAME_DESC, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new StaffInfoEditorSupport(tableViewer, 14, this);
		createColumn("住址", BrandInfoSorter.NAME_ASC, BrandInfoSorter.NAME_DESC,
				editingSupport);
		manager.addITextKeyChangeListener(editingSupport);
		editingSupport = new StaffInfoEditorSupport(tableViewer, 15, this);
		createColumn("基本工资", BrandInfoSorter.NAME_ASC,
				BrandInfoSorter.NAME_DESC, editingSupport);
		manager.addITextKeyChangeListener(editingSupport);

		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		// initial the tabelViewer
		tableViewer.setContentProvider(new StaffInfoContentProvider());
		tableViewer.setLabelProvider(new StaffInfoLabelProvider());
		initial();
		tableViewer.setInput(list);
		table.addListener(SWT.EraseItem, new SetTableColColorListener(table));

		table.select(0);
		table.setFocus();

	}

	@Override
	public void create() {
		Shell subshell = new Shell(shell, SWT.DIALOG_TRIM);
		StaffInfoCreate sb = new StaffInfoCreate(subshell, tableViewer);
		sb.open();
		if (!sb.isCacel()) {
			list = sb.getList();
			tableViewer.setInput(list);
			save();

		} else {
			list = (List) tableViewer.getInput();
		}
		infoLabel.setText("提示：添加新数据后请点击保存来更新数据！");
		tableViewer.getTable().select(list.size() - 1);
	}

	@Override
	public void delete() {
		IStructuredSelection selection = (IStructuredSelection) tableViewer
				.getSelection();
		Yginfo staff = (Yginfo) selection.getFirstElement();
		if (!selection.isEmpty()) {
			if (MessageDialog.openConfirm(null, "提示", "你确定删除数据吗？")) {
				delete(staff);
			}
		} else {
			MessageDialog.openConfirm(null, "提示", "请从表格中选择一行数据进行删除！");
		}
	}

	private void delete(Yginfo staff) {
		String id = staff.getYgid();
		if (!id.isEmpty()) {
			int[] idBuffer = { 0 };
			Object[] idObject = { id };
			List result = (List) DbManager.getInstance().search(
					"com.whlilong.jxc.ui.getstaffid", idBuffer, idObject);
			Yginfo dpt = (Yginfo) result.get(0);
			DbManager.getInstance().delete(dpt);
		}
		refresh();
	}

	@Override
	public void print() {
		// TODO Auto-generated method stub
		final PDocument doc = new PDocument("print");

		PTextBox t;

		t = new PTextBox(doc);

		t.setText("武汉立隆客商信息");

		new PVSpace(doc, 0.5);
		new PHLine(doc, 0.02, SWT.COLOR_RED);
		new PVSpace(doc, 0.5);

		// create the table
		SWTPTable swttable = new SWTPTable(doc);
		swttable.setTable(table);
		swttable.setBoxProvider(new PTableBoxProvider());
		
		PrintPreview pr = new PrintPreview(null, "信息打印", IconSource
				.getImage("print"), doc);
		pr.onPrint();
	}

	@Override
	public void refresh() {
		initial();
		treeViewer.setInput(extentionInfo.getInstance().getStaffTreeInfo());
		treeViewer.expandToLevel(2);
		tableViewer.setInput(list);
	}

	@Override
	public void save() {
		if (!isSave) {
			MessageDialog.openWarning(null, "提示", "数据不能保存！");
			return;
		}
		manager.notifyListener();
		Iterator data = list.iterator();
		if (!data.hasNext()) {
			MessageDialog.openWarning(null, "提示", "没有需要保存的数据！");
			return;
		}

		Job job = new Job("正在保存数据。。。") {
			@Override
			protected IStatus run(IProgressMonitor monitor) {
				// TODO Auto-generated method stub
				monitor.beginTask("正在保存数据。。。", IProgressMonitor.UNKNOWN);
				for (int i = 0; i < list.size(); i++) {
					Yginfo staffInfo = (Yginfo) list.get(i);
					int id = staffInfo.getId();
					int[] idBuffer = { 0 };
					Object[] idObject = { id };
					List result = (List) DbManager.getInstance().search(
							"com.whlilong.jxc.ui.getStaffInfo.getId", idBuffer,
							idObject);
					if (result.size() > 0) {
						String staffName = staffInfo.getYgname();
						String staffId = staffInfo.getYgid();
						if (staffId != null && !staffId.equals("")
								&& staffName != null && !staffName.equals("")) {
							int count = 0;
							Yginfo k = (Yginfo) result.get(0);
							k.setId(id);
							k.setYgid(staffId);
							k.setYgname(staffName);
							k.setAddress(staffInfo.getAddress());
							k.setBirthday(staffInfo.getBirthday());
							k.setCardid(staffInfo.getCardid());
							k.setDate(staffInfo.getDate());
							k.setJdgz(staffInfo.getJdgz());
							k.setPartname(staffInfo.getPartname());
							k.setStatus(staffInfo.getStatus());
							k.setTag(staffInfo.getTag());
							k.setTel(staffInfo.getTel());
							k.setXb(staffInfo.getXb());
							k.setXlname(staffInfo.getXlname());
							k.setZwname(staffInfo.getZwname());
							
							monitor.worked(1);
							DbManager.getInstance().update(k);
						} else {
							return Status.CANCEL_STATUS;
						}

					} else {
						String staffName = staffInfo.getYgname();
						String staffId = staffInfo.getYgid();
						if (staffId != null && !staffId.equals("")
								&& staffName != null && !staffName.equals("")) {
							Yginfo ks = new Yginfo();
							ks.setId(id);
							ks.setYgid(staffId);
							ks.setYgname(staffInfo.getYgname());
							ks.setYgid(staffId);
							ks.setYgname(staffName);
							ks.setAddress(staffInfo.getAddress());
							ks.setBirthday(staffInfo.getBirthday());
							ks.setCardid(staffInfo.getCardid());
							ks.setDate(staffInfo.getDate());
							ks.setJdgz(staffInfo.getJdgz());
							ks.setPartname(staffInfo.getPartname());
							ks.setStatus(staffInfo.getStatus());
							ks.setTag(staffInfo.getTag());
							ks.setTel(staffInfo.getTel());
							ks.setXb(staffInfo.getXb());
							ks.setXlname(staffInfo.getXlname());
							ks.setZwname(staffInfo.getZwname());
							DbManager.getInstance().insert(ks);
						} else {

							return Status.CANCEL_STATUS;
						}

					}
				}
				monitor.done();
				return Status.OK_STATUS;
			}

		};
		job.addJobChangeListener(new JobChangeAdapter() {
			public void done(IJobChangeEvent event) {
				final boolean isSuccess = event.getResult().isOK();
				Display.getDefault().asyncExec(new Runnable() {
					public void run() {
						if (isSuccess) {

							MessageDialog.openInformation(null, "提示",
									"数据已经成功保存！");
							treeViewer.setInput(extentionInfo.getInstance()
									.getStaffTreeInfo());
							treeViewer.refresh();
							treeViewer.expandToLevel(2);

						} else
							MessageDialog.openError(null, "错误",
									"编号或名称为空，数据保存失败！");
					}
				});
			}
		});
		job.setUser(false);
		job.setPriority(Job.SHORT);
		job.schedule();

	}

	@Override
	public void search() {
		staffId = staffNoText.getText();
		staffName = staffNameText.getText();
		find(staffId, staffName);
	}

	private void find(String id, String name) {
		// TODO Auto-generated method stub
		if ((id == null || id.equals("")) && (name == null || name.equals(""))) {
			tableViewer.setInput(getStaffinfo(null, null));
		} else if ((id != null || !id.equals(""))
				&& (name == null || name.equals(""))) {
			tableViewer.setInput(getStaffinfo(id, null));
		} else if ((id == null || id.equals(""))
				&& (name != null || !name.equals(""))) {
			tableViewer.setInput(getStaffinfo(null, name));
		} else {
			tableViewer.setInput(getStaffinfo(id, name));
		}
	}

	@Override
	public void searchByCondition() {

	}

	@Override
	public void addInfo() {
		// TODO Auto-generated method stub

	}

	@Override
	public List getList() {
		// TODO Auto-generated method stub
		return this.list;
	}

	@Override
	public void noticeFault(String message) {
		infoLabel.setForeground(Display.getCurrent().getSystemColor(
				SWT.COLOR_RED));
		infoLabel.setText(message);
		this.isSave = false;
	}

	@Override
	public void noticeSuccess() {
		infoLabel.setText("");
		this.isSave = true;
	}

	@Override
	public void preprint() {
		// TODO Auto-generated method stub
		final PDocument doc = new PDocument("print");

		PTextBox t;

		t = new PTextBox(doc);

		t.setText("武汉立隆客商信息");

		new PVSpace(doc, 0.5);
		new PHLine(doc, 0.02, SWT.COLOR_RED);
		new PVSpace(doc, 0.5);

		// create the table
		SWTPTable swttable = new SWTPTable(doc);
		swttable.setTable(table);
		swttable.setBoxProvider(new PTableBoxProvider());
		
		PrintPreview pr = new PrintPreview(null, "信息打印", IconSource
				.getImage("print"), doc);
		pr.open();
	}

}
